import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;

public class Ejercicio8 {

	public static void main(String[] args) {
		if (args[0].equals("R")) {
			FileReader fr = null;
			BufferedReader br = null;
					
			try {
				fr = new FileReader("src/dat/clientes.txt");
				br = new BufferedReader(fr);
				String linea;
				Collection<Persona> c = new ArrayList<Persona>();
				while ((linea = br.readLine()) != null) {
					String[] palabras = linea.split(":");
					int dni=Integer.parseInt(palabras[0]);
					String nombre=palabras[1];
					c.add(new Persona(dni, nombre));
					System.out.println(linea);
				}
				for (Persona p : c) {
					System.out.println(p);
				}
			
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (fr != null) {
						fr.close();
					}
				} catch (Exception e2) {
					System.out.println("Error al cerrar");
				}
			}
		} else if (args[0].equals("W")) {
			FileReader fr = null;
			FileWriter fw = null;
			PrintWriter pw = null;

			Collection<Persona> c = new ArrayList<Persona>();
			int dni;
			String nombre;

			for (int x = 1; x < args.length; x += 2) {
				dni = Integer.parseInt(args[x]);
				nombre = args[x + 1];
				c.add(new Persona(dni, nombre));
			}
			for (Persona p : c) {
				System.out.println(p);
			}
			try {

				fw = new FileWriter("src/dat/clientes.txt");
				pw = new PrintWriter(fw);

				for (int x = 1; x < args.length; x += 2) {
					dni = Integer.parseInt(args[x]);
					nombre = args[x + 1];
					pw.println(dni + ":" + nombre);
				}

				System.out.println("Fichero escrito correctamente");
			}

			catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (fr != null) {
						fr.close();
					}
					if (fw != null) {
						fw.close();
					}
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}
	}
}
